import time,urllib2,urllib,sys,re,string

def task():	
	url = "http://nc.tju.edu.cn/query/ipFlow.asp"
	ip = [59,67,33,8]
	year = time.strftime('%Y',time.localtime(time.time()))
	month = time.strftime('%m',time.localtime(time.time()))
	day = time.strftime('%d',time.localtime(time.time()))
	if day < 15:
		if month == 1:
			month = 12
			year = year - 1
		else:
			month = month - 1
	print month
	flows = 0.0 
	last_day_flow = ''
	j=0
	search = urllib.urlencode([('ip1',ip[0]),('ip2',ip[1]),('ip3',ip[2]),('ip4',ip[3]),('year1',year),('month1',month)])
	req = urllib2.Request(url)
	fd = urllib2.urlopen(req,search)
	patt1 = '<div align="center">.*'
	patt2 = '(<div align="center">)(.*)(</div></td>)'
	p = re.compile(patt2)
	tag = 0
	i = 0
	for line in fd.readlines():
		if tag:
			t = string.atof(line.strip().replace(',',''))
			flows = t / 1024.0
			tag = 0
			j += 1
		else:	
			m = re.search(patt1,line)
			if m is not None:
				data = m.group()
				last_day_flow = data
				if len(data) < 25:
					print data
					tag = 1
	start = last_day_flow.find(">")
	end = last_day_flow.find("</")
	today_flow = last_day_flow[start+1:end] 
	print today_flow
	cur_time = time.strftime('%H:%M:%S',time.localtime(time.time()))
	cur_flow = string.atof(today_flow.strip().replace(',',''))
	#write_to_file(cur_time,cur_flow)

def write_to_file(cur_time,cur_flow):
	#print cur_time,cur_flow
	file_name = "stat-" + time.strftime('%Y-%m-%d',time.localtime(time.time())) + ".txt"
	fid = open(file_name,'a')
	content = cur_time + ' ' + str(cur_flow) + '\n'
	fid.write(content)
	fid.close()
	
def main(n):
	t = time.time()
	start_t = t
	end_t = start_t + 60*60*120
	while True:
		task()
		time.sleep(n)
		t = time.time()

if __name__ == "__main__":
	#main(10)
	task()
